﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Sy;
using SYBOMnt = Texfina.BOMnt.Sy;
using SYBOQry = Texfina.BOQry.Sy;

namespace SY
{
   public partial class wfUsuarioMnt : EditPage
   {

      public const int _GRDLIST_STLASTOPT = 4;
      public const int _GRDLIST_STANULADO = 6;

      private byte[] _bytPK = null;

      private string IdUser
      {
         get { return this.ViewState["_idUser"].ToString(); }
         set { this.ViewState["_idUser"] = value; }
      }

      protected void Page_Load(object sender, EventArgs e)
      {
         if (this.IsPostBack)
         {
            this.LoadInPostBack();
            return;
         }
         this.LoadData();
      }

      public override void LoadInPostBack()
      {
         this.RegisterGeneralScripts();
         this.LockControls();

         if (this.DataSource != null)
         {
            grdList.DataSource = this.DataSource;
            grdList.DataBind();
         }

      }

      public override void LoadInitialSettings()
      {
         this.FormEditAction = (FormEditAction)Enum.Parse(typeof(FormEditAction), Request.QueryString["formEA"]);
         this.SetInitialTitle("Usuarios");
      }

      public override void DataToControls()
      {
         EUsuario objE = new EUsuario();
         IBOQuery objBO = WCFHelper.GetObject<IBOQuery>(typeof(SYBOQry.Usuario));

         this.IdUser = "";

         objE.IdUser = Request.QueryString["idUser"];
         objE = (EUsuario)objBO.GetByKey(objE);

         if (objE != null)
         {

            this.IdUser = objE.IdUser;
            WebHelper.EntityToControl(objE, "IdLogon", txtidLogon);
            WebHelper.EntityToControl(objE, "DsNombres", txtdsNombres);

            _bytPK = objE.IdClavePub;
         }
         else
            objE = new EUsuario();

         SYBOQry.IUsuario objBODet = WCFHelper.GetObject<SYBOQry.IUsuario>(typeof(SYBOQry.Usuario));
         DataTable dt = objBODet.GetConfigMenu(objE);

         this.GridSetDataBinding(grdList, dt);

      }

      public override void RegisterGeneralScripts()
      {

         StringBuilder sb = new StringBuilder();

         sb.AppendLine("function validate" + bttListAD.ID + "(){");
         sb.AppendLine("disableControl('" + bttListAD.ClientID + "',true);");
         sb.AppendLine("var varRet = bandejaModal('wfUsuADBnd.aspx');");
         sb.AppendLine("disableControl('" + bttListAD.ClientID + "',false);");
         sb.AppendLine("if(varRet==null)");
         sb.AppendLine("return false;");

         sb.AppendLine("setInputValue('" + txtidLogon.ClientID + "',varRet[0]);");
         sb.AppendLine("setInputValue('" + txtdsNombres.ClientID + "',varRet[1] + ' ' + varRet[2]);");
         sb.AppendLine("return false;}");

         sb.AppendLine("function validateEditForm(key){");

         sb.AppendLine("var varRpta = isEmptyControl('" + this.txtidLogon.ClientID + "','Ingrese el Usuario');");
         sb.AppendLine("if(varRpta==true)");
         sb.AppendLine("return !varRpta;");
         sb.AppendLine("varRpta = isEmptyControl('" + this.txtdsNombres.ClientID + "','Ingrese los Nombres y Apellidos');");
         sb.AppendLine("if(varRpta==true)");
         sb.AppendLine("return !varRpta;");

         sb.AppendLine("menu_doPostBack('" + mnuToolbar.ClientID + "','" + mnuToolbar.UniqueID + "',key);");
         sb.AppendLine("}");

         bttListAD.OnClientClick = "return validate" + bttListAD.ID + "();";

         ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);
      }

      public override void LockControls()
      {

         switch (this.FormEditAction)
         {
            case FormEditAction.Edit:
               txtidLogon.Attributes.Add("readonly", "true");
               bttListAD.Attributes.Add("disabled", "true");
               break;
         }

         if (User.Identity.AuthenticationType == ConstAuthenticationType.LDAP)
         {
            txtidLogon.Attributes.Add("readonly", "true");
            txtdsNombres.Attributes.Add("readonly", "true");
         }

      }

      protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
      {
         if (e.Item == null)
            return;

         switch (e.Item.Value)
         {
            case ConstMenuToolbarValue.BUTTON_SAVE:
            case ConstMenuToolbarValue.BUTTON_SAVENEW:
               if (this.FormEditAction != FormEditAction.Delete)
                  this.SaveData(e.Item.Value);
               else
                  this.DeleteData();
               break;

            case ConstMenuToolbarValue.BUTTON_EXIT:
               this.Response.Redirect("wfUsuarioBnd.aspx?Filter=1");
               break;
         }

      }

      public override void SaveData(String key)
      {
         if (this.ValidateData() == false)
            return;

         IEntityBase objE = (IEntityBase)this.CreateEntitySet();

         IBOUpdate objBO = WCFHelper.GetObject<IBOUpdate>(typeof(SYBOMnt.Usuario));

         string[] strRet = objBO.UpdateData(objE);
         string strMsg = "";

         switch (this.FormEditAction)
         {

            case FormEditAction.AddNew:
            case FormEditAction.Copy:
               strMsg = "Se ha registrado el Usuario : " + txtidLogon.Text;
               break;
            default:
               strMsg = "Se ha modificado el Usuario : " + txtidLogon.Text;
               break;
         }

         this.hdnMsgOPB.Value = this.CreatePostbackMessage("CORRECTO", strMsg, TypeMessageAlert.correct, false, "wfUsuarioBnd.aspx?Filter=1");
         ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "msgPB", "MessageOnPostback();", true);
      }

      public override Object CreateEntitySet()
      {
         EUsuario objE = new EUsuario();

         if (this.FormEditAction == FormEditAction.AddNew || this.FormEditAction == FormEditAction.Copy)
            objE.EntityState = EntityState.Added;
         else
         {
            IBOQuery objBO = WCFHelper.GetObject<IBOQuery>(typeof(SYBOQry.Usuario));
            objE.IdUser = this.IdUser;
            objE = (EUsuario)objBO.GetByKey(objE);

            if (this.FormEditAction == FormEditAction.Edit)
               objE.EntityState = EntityState.Modified;
            if (this.FormEditAction == FormEditAction.Delete)
               objE.EntityState = EntityState.Deleted;
         }

         WebHelper.ControlToEntity(txtidLogon, objE, "IdLogon");
         WebHelper.ControlToEntity(txtdsNombres, objE, "DsNombres");

         if (objE.IdClavePub == null)
         {
            Guid guidPk = Guid.NewGuid();
            objE.IdClavePub = guidPk.ToByteArray();
         }

         objE.StCamPswPrx = ConstFlagEstado.DESACTIVADO;
         objE.StNoCamPsw = ConstFlagEstado.DESACTIVADO;
         objE.StNoExpira = ConstFlagEstado.DESACTIVADO;
         objE.StRegSist = ConstFlagEstado.DESACTIVADO;

         if (this.FormEditAction == FormEditAction.Delete)
            objE.StAnulado = ConstFlagEstado.ACTIVADO;
         else
            objE.StAnulado = ConstFlagEstado.DESACTIVADO;

         IList<EUsuMenu> colE = new List<EUsuMenu>();
         Cryptor objEnc = new Cryptor();

         foreach (GridViewRow grdRow in grdList.Rows)
         {

            DataRow dr = this.GridGetRowFromDataKey(grdList, Convert.ToInt32(grdRow.RowIndex));

            if (dr["stLastOpt"].ToString() == ConstFlagEstado.DESACTIVADO)
               continue;

            CheckBox chk = null;

            char[] arrChr = new char[6];
            arrChr[0] = Convert.ToChar(ConstFlagEstado.DESACTIVADO);
            arrChr[1] = Convert.ToChar(ConstFlagEstado.DESACTIVADO);
            arrChr[2] = Convert.ToChar(ConstFlagEstado.DESACTIVADO);
            arrChr[3] = Convert.ToChar(ConstFlagEstado.DESACTIVADO);
            arrChr[4] = Convert.ToChar(ConstFlagEstado.DESACTIVADO);
            chk = (CheckBox)grdRow.FindControl("chkFull");
            arrChr[5] = Convert.ToChar(chk.Checked ? ConstFlagEstado.ACTIVADO : ConstFlagEstado.DESACTIVADO);

            string strNew = new string(arrChr);

            if (strNew == new string(Convert.ToChar(ConstFlagEstado.DESACTIVADO), 6))
               continue;

            byte[] bytR = objEnc.Encrypt(strNew, objE.IdClavePub);

            EUsuMenu objEUsu = new EUsuMenu();

            objEUsu.EntityState = EntityState.Added;
            objEUsu.IdUser = this.IdUser;
            objEUsu.IdMenu = dr["idMenu"].ToString();
            objEUsu.IdDerechos = bytR;
            objEUsu.StAnulado = ConstFlagEstado.DESACTIVADO;
            colE.Add(objEUsu);
         }

         EUsuarioSet objESet = new EUsuarioSet();

         objESet.Usuario = objE;
         objESet.UsuMenu = colE;

         return objESet;
      }

      protected void grdList_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
         if (e.Row.RowType == DataControlRowType.DataRow)
         {

            e.Row.ID = e.Row.RowIndex.ToString();

            ImageButton btt = (ImageButton)e.Row.FindControl("grdBttOption");
            btt.OnClientClick = "return false;";

            CheckBox chk = null;

            if (e.Row.Cells[_GRDLIST_STLASTOPT].Text == ConstFlagEstado.ACTIVADO)
            {
               if (_bytPK != null)
               {
                  Cryptor objEnc = new Cryptor();
                  DataRowView drv = (DataRowView)e.Row.DataItem;

                  if (drv["idDerechos"] != DBNull.Value)
                  {
                     byte[] byteD = objEnc.Decrypt((byte[])drv["idDerechos"], _bytPK);

                     chk = (CheckBox)e.Row.FindControl("chkFull");
                     chk.Checked = (Convert.ToChar(byteD[5]) == '1') ? true : false;
                  }

               }

               btt.ImageUrl = ConstSistema.ROOT_ENA_ICONS_PATH + "/EditOption.png";
            }
            else
            {
               chk = (CheckBox)e.Row.FindControl("chkFull");
               chk.Visible = false;
            }

            if (e.Row.Cells[_GRDLIST_STANULADO].Text == ConstFlagEstado.ACTIVADO)
               e.Row.ForeColor = System.Drawing.Color.Red;
         }

      }
   }
}